<template>
  <div>
    <div class="createTest testPaper">
      <el-card
        class="title"
        v-loading="isLoading"
        element-loading-text="更新中"
      >
        <el-row>
          <el-col :span="23"
            ><div class="grid-content">
              <el-input
                v-model="examData.examTitle"
                class="testName"
                placeholder="请输入内容"
              ></el-input></div
          ></el-col>
          <el-col :span="1">
            <el-button type="primary" @click="save()"
              >保存<i class="el-icon-plus"></i
            ></el-button>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="6"
            ><div class="grid-content">
              <el-cascader
                v-model="path"
                :options="examOptions"
                @change="examCategorychange"
                :props="{ value: 'id', label: 'categoryName' }"
                placeholder="请选试卷分类"
              ></el-cascader></div
          ></el-col>
          <el-col :span="6"
            ><div class="grid-content">
              <el-tag>答题时间:</el-tag>
              <el-input-number
                v-model="examData.limitTime"
                controls-position="right"
                :step="10"
                size="mini"
                :min="1"
              />
              分钟
            </div></el-col
          >
          <el-col :span="6"
            ><div class="grid-content">
              <el-tag type="info" class="test-info">
                题目数量: 共
                {{
                  topicNavIndex_mixin(
                    4,
                    this.examData.groupedQuestions[4].questions.length - 1
                  )
                }}
                道
              </el-tag>
            </div></el-col
          >
          <el-col :span="6">
            <div class="grid-content">
              <el-tag class="test-info">总分: {{ totalScore }} 分</el-tag>
            </div>
          </el-col>
        </el-row>
      </el-card>
      <el-row>
        <el-col class="topics" :span="19">
          <div>
            <el-card>
              <synthesis-edit-form
                ref="editForm"
                :item="examData.groupedQuestions[currentGroupIndex]"
                :groupedIndex="currentGroupIndex"
                :prefix-index="getPrefixIndex"
              ></synthesis-edit-form>
            </el-card>
            <el-button
              v-if="
                this.currentGroupIndex !== 0 &&
                this.examData.groupedQuestions[
                  this.currentGroupIndex === 0 ? 0 : this.currentGroupIndex - 1
                ].questions.length !== 0
              "
              @click="lastGroup"
              type="primary"
              >上一大题</el-button
            >
            <el-button
              v-if="
                this.currentGroupIndex !== 4 &&
                this.examData.groupedQuestions[
                  this.currentGroupIndex === 4 ? 4 : this.currentGroupIndex + 1
                ].questions.length !== 0
              "
              @click="nextGroup"
              type="primary"
              >下一大题</el-button
            >
          </div>
        </el-col>
        <el-col class="topic-nav">
          <el-card :class="isFixed ? 'isFixed' : ''">
            <!-- 导航按钮 -->
            <ul
              v-for="(item, groupedIndex) in examData.groupedQuestions"
              :key="groupedIndex"
            >
              <div class="topic-nav-item" v-if="item.rootName">
                <div class="nav-title">
                  <el-button
                    size="mini"
                    plain
                    @click="topicNav(groupedIndex, 0)"
                  >
                    {{ returnCN(groupedIndex + 1) }}
                  </el-button>
                  <el-tag>
                    {{ item.rootName }}
                  </el-tag>
                </div>
                <span
                  class="topic-nav-button"
                  v-for="(question, questionIndex) in item.questions"
                  :key="questionIndex"
                  @click="topicNav(groupedIndex, questionIndex)"
                  :class="isEdit(groupedIndex, questionIndex) ? 'isEdit' : ''"
                >
                  {{ topicNavIndex_mixin(groupedIndex, questionIndex) }}
                </span>
              </div>
            </ul>
          </el-card>
        </el-col>
      </el-row>
    </div>
  </div>
</template>

<script>
import "@/assets/less/testPaper.less";
import testPaperMixin from "@/utils/testPaper-mixin";
import Upload from "@/views/modules/oss/oss-upload.vue";
import SynthesisEditForm from "./synthesis-edit-form";

export default {
  components: {
    SynthesisEditForm,
    Upload,
  },
  name: "examUpload",
  mixins: [testPaperMixin],
  data() {
    return {
      currentGroupIndex: 0,
      typeId: 1,
      path: [],
      excludeId: 1,
      isLoading: false,
      index: 0,
      //试卷分类选项
      examOptions: [],
      questionTypeOptions: [],
      idList: [
        {
          id: 0,
          list: [],
        },
        {
          id: 1,
          list: [],
        },
        {
          id: 2,
          list: [],
        },
        {
          id: 3,
          list: [],
        },
        {
          id: 4,
          list: [],
        },
      ],
      uploadVisible: false,
      //控制设置统一分数按钮输入是否显示
      showAllScores: [
        {
          id: 0,
          showAllScore: false,
        },
        {
          id: 1,
          showAllScore: false,
        },
        {
          id: 2,
          showAllScore: false,
        },
        {
          id: 3,
          showAllScore: false,
        },
        {
          id: 4,
          showAllScore: false,
        },
      ],
      //选项前缀
      prefixs: ["A", "B", "C", "D"],
      //侧导航栏是否悬浮
      isFixed: false,
      //试卷数据
      examData: {
        id: "",
        examTitle: "点击编辑试卷名称",
        categoryId: 0,
        type: 0,
        limitTime: 60,
        totalScore: 0.0,
        groupedQuestions: [
          {
            rootName: "常识判断",
            score: 1.0,
            questions: [],
          },
          {
            rootName: "言语理解与表达",
            score: 1.0,
            questions: [],
          },
          {
            rootName: "数量关系",
            score: 1.0,
            questions: [],
          },
          {
            rootName: "判断推理",
            score: 1.0,
            questions: [],
          },
          {
            rootName: "资料分析",
            score: 1.0,
            questions: [],
          },
        ],
      },
      //当前编辑的题目索引
      editInedx: {
        type: "-1",
        index: "-1",
        input: "-2",
      },
    };
  },

  computed: {
    //改成计算所在表单之前题数
    getPrefixIndex() {
      //2021-1212 计算前缀
      let index = 0;
      for (let i = 0; i < this.currentGroupIndex; i++) {
        index += this.examData.groupedQuestions[i].questions.length;
      }
      return index;
    },
    //试卷总分
    totalScore() {
      let score = 0;
      this.examData.groupedQuestions.forEach((element) => {
        score += element.score * element.questions.length;
      });
      this.examData.totalScore = parseFloat(score.toFixed(2));
      return this.examData.totalScore;
    },
  },
  created() {
    this.getExamOptions();
    this.edit(0, 0);
  },
  mounted() {
    // 监听滚动事件，然后用handleScroll这个方法进行相应的处理
    window.addEventListener("scroll", this.handleScroll);
  },
  methods: {
    lastGroup() {
      this.currentGroupIndex =
        this.currentGroupIndex === 0 ? 0 : this.currentGroupIndex - 1;
      window.scrollTo(0, 0);
    },
    nextGroup() {
      this.currentGroupIndex =
        this.currentGroupIndex === 4 ? 4 : this.currentGroupIndex + 1;
      window.scrollTo(0, 0);
    },
    init(examData) {
      if (examData) {
        this.examData = examData;
        this.examData.groupedQuestions.forEach((element, groupedIndex) => {
          element.questions.forEach((question, questionIndex) => {
            //处理每个题目的选项,分割\n符得到选项数组
            question.choice = question.choice.split("\n");
            //如果包含【资料】信息,则用\n截取
            if (question.questionTopic.indexOf("【资料】") != -1) {
              question.questionTopic = question.questionTopic.split("\n");
            }
          });
        });
      }
      let id = this.examData.categoryId;
      this.$http({
        url: this.$http.adornUrl(`/exam/examcategory/path/${id}`),
        method: "post",
      }).then(({ data }) => {
        if (data && data.code === 0) {
          this.path = data.path;
        } else {
          this.path = [];
        }
      });
    },
    //获取试卷分类选项
    getExamOptions() {
      this.$http({
        url: this.$http.adornUrl(`/exam/examcategory/tree`),
        method: "post",
        data: this.excludeId,
      }).then(({ data }) => {
        if (data && data.code === 0) {
          this.examOptions = data.data;
        } else {
          this.examOptions = [];
        }
      });
    },
    //判断题文是否包含资料
    isData(questionTopic) {
      if (questionTopic instanceof Array) {
        return true;
      }
      return false;
    },
    //考试分类变化时触发的事件
    examCategorychange(value) {
      let id = value[value.length - 1];
      this.examData.categoryId = id;
    },
    //校验数据合法性
    validate() {
      if (!this.examData.examTitle) {
        this.$message.error("试卷标题不能为空!");
        return false;
      }
      if (!this.examData.limitTime) {
        this.$message.error("考试时限不能为空!");
        return false;
      }
      return true;
    },
    //保存试卷事件
    async save() {
      const validate = this.validate();
      if (!validate) {
        return false;
      }
      let uploadData = JSON.parse(JSON.stringify(this.examData));
      uploadData.groupedQuestions.forEach((element, groupedIndex) => {
        element.questions.forEach((question, questionIndex) => {
          if (this.isData(question.questionTopic)) {
            question.questionTopic =
              question.questionTopic[0] + "\n" + question.questionTopic[1];
          }
          question.choice =
            question.choice[0] +
            "\n" +
            question.choice[1] +
            "\n" +
            question.choice[2] +
            "\n" +
            question.choice[3];
          question.sort = this.topicNavIndex_mixin(groupedIndex, questionIndex);
        });
      });
      this.isLoading = true;

      await this.$http({
        url: this.$http.adornUrl(`/exam/exam/update/linetest`),
        method: "post",
        data: this.$http.adornData(uploadData),
      }).then(({ data }) => {
        if (data && data.code === 0) {
          this.$message.success(data.msg);
          this.$router.push({
            name: `exam-list`,
          });
        } else {
          this.$message.error(data.msg);
        }
        this.isLoading = false;
        Object.assign(this.$data.examData, this.$options.data().examData);
        this.$parent.changeState();
      });
    },
    //设置当前编辑中的题目
    edit(type, index) {
      if (this.editInedx.type == type && this.editInedx.index == index) {
        return;
      }
      this.editInedx.type = type;
      this.editInedx.index = index;
    },
    //是否在编辑状态
    isEdit(type, index) {
      if (this.editInedx.type == type && this.editInedx.index == index) {
        return true;
      } else {
        return false;
      }
    },
    //滚动事件
    handleScroll() {
      let scrollTop =
        window.pageYOffset ||
        document.documentElement.scrollTop ||
        document.body.scrollTop; // 滚动条偏移量
      if (scrollTop > 200) {
        this.isFixed = true;
      } else {
        this.isFixed = false;
      }
    },

    //点击题号导航跳转
    //修改后无需total跳转 --Geralt
    topicNav(type, index) {
      let time = 100;
      if (this.currentGroupIndex != type) {
        time = 800;
        this.currentGroupIndex = type;
      }
      setTimeout(() => {
        let top = document.getElementsByClassName("topic-content")[index]
          .offsetTop;
        window.scrollTo({ top: top + 220, behavior: "smooth" });
      }, time);
      this.edit(type, index);
    },
  },
};
</script>

<style scoped>
.el-row {
  margin-bottom: 20px;
}
.el-col {
  border-radius: 4px;
}

.grid-content {
  border-radius: 4px;
  min-height: 36px;
}
.row-bg {
  padding: 10px 0;
}
</style>
